#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <string>

#define THD_NUM 3

pthread_mutex_t mtx;
pthread_cond_t cond;

void* boss_run(void* args){
  std::string name = (char*)args;
  while (true){
    //唤醒在条件变量下的一个进程
    std::cout << "master say begin work" << std::endl;
    //pthread_cond_signal(&cond);
    pthread_cond_broadcast(&cond);
    sleep(1);
  }
}

void* worker_run(void* args){
  int id = *(int*)args;
  delete (int*)args;
  while (true){
    pthread_cond_wait(&cond, &mtx);
    std::cout << "worker " << id << " is working ..." << std::endl;
    sleep(1);
  }
}

int main(){

  pthread_mutex_init(&mtx, NULL);
  pthread_cond_init(&cond, NULL);

  pthread_t master;
  pthread_t tid_arr[THD_NUM];

  pthread_create(&master, NULL, boss_run, (void*)"boss");
  for (int i = 0; i < THD_NUM; i++){
    int* number = new int(i); 
    pthread_create(tid_arr + i, NULL, worker_run, (void*)number);
  }

  pthread_join(master, NULL);
  for (int i = 0; i < THD_NUM; i++){
    pthread_join(tid_arr[i], NULL);
  }

  pthread_mutex_destroy(&mtx);
  pthread_cond_destroy(&cond);
  return 0;

}

